# coding: utf-8
import pymysql
import re

forecastResult = {}
weatherDist = {}
weatherList = []
highs = []
lows = []
weathers = []
winds = []
defaultCity = []
defaultForecastDate = []

conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='admin',
                       database='weather', charset='utf8')
cursor = conn.cursor()

# isFindWeather是要查询的日期，根据这个去数据库查以往这个月日的天气
def getBeforInDateBase(isFindWeather):
    for i in range(2011, 2020):
        year = str(i)
        month= str(re.findall("\d{2}", isFindWeather)[2])
        day = str(re.findall("\d{2}", isFindWeather)[3])
        queryDate = year + '-' + month + '-' + day
        findsql =  "select * from forecast where DATE_FORMAT(date,'%Y-%m-%d')="+"'"+queryDate+"'"
        cursor.execute(findsql)
        result = cursor.fetchall()[0]
        # print(result)
        city = result[1]
        weather = result[2]
        # 这里可能是因为日期是date类型，占了两个位置，所以跳了一个
        highTemterature = str(result[4])
        lowTemterature = str(result[5])
        wind = result[6]
        # 因为元组不可修改，这里格式化日期没搞好，只能重新加一遍
        tup = (city, weather, queryDate, highTemterature, lowTemterature, wind)
        # print('城市：' + city + ' 天气:' + weather + ' 日期：' + queryDate + ' 最高气温：'
        #       +highTemterature + ' 最低气温：' + lowTemterature  + ' 风向：' + wind)
        weatherList.append(tup)
    return weatherList

def forecast(forecastDate):
    getBeforInDateBase(forecastDate)
    # print(weatherList)
    for i in range(len(weatherList)):
        defaultCity.append(weatherList[i][0])
        weather = weatherList[i][1]
        # defaultForecastDate.append(forecastDate)
        highTemterature = str(weatherList[i][3])
        lowTemterature = str(weatherList[i][4])
        wind = weatherList[i][5]
        # print('城市：' + city + ' 天气:' + weather + ' 日期：' + date + ' 最高气温：'
        #        +highTemterature + ' 最低气温：' + lowTemterature  + ' 风向：' + wind)
        highs.append(highTemterature)
        lows.append(lowTemterature)
        weathers.append(weather)
        winds.append(wind)
    forecastResult['城市'] = defaultCity[0]
    forecastResult['日期'] = forecastDate
    forecastResult['预测天气'] = compareStr(weathers)
    forecastResult['预测最高温度'] = compareStr(highs)
    forecastResult['预测最低温度'] = compareStr(lows)
    forecastResult['预测风向'] = compareStr(winds)
    # print(forecastResult)
    return forecastResult

def compareStr(list):
    fakeDist = {}
    max_key = None
    for i in list:
        if i not in fakeDist:
            # 计算元素出现的次数
            count = list.count(i)
            # 保存到字典中
            fakeDist[i] = count
            # 记录次数最大的元素,返回max_key的值，如果值不在字典中返回default值
            if count > fakeDist.get(max_key, 0):
                max_key = i
    return max_key

# forecast('2020-03-11')



